package com.xm.servlet.admin;

import com.jspsmart.upload.File;
import com.jspsmart.upload.Files;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * @author Administrator
 * @create 2020-09-21 10:32
 * @desc 文件上传处理器
 **/
@WebServlet("/upload.do")
public class UploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接受from传过来的的文件
        SmartUpload smartUpload = new SmartUpload();
        //初始化文件上传对象，将配置信息，以及请求、响应对象给文件上传的对象托管
        smartUpload.initialize(getServletConfig(),req,resp);
        try {
            //调用文件上传的方法
            smartUpload.upload();
            Files files = smartUpload.getFiles();
            for (int i = 0; i < files.getSize(); i++) {
                File file = files.getFile(i);
                //将文件名或文件保存到数据库中
                String fileName = UUID.randomUUID().toString()+"."+file.getFieldName();
                System.out.println("你要上传的文件名："+fileName);
            }
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
